<template lang="pug">
  div.h-100.w-100
    div.h-100.monaco-editor-box(v-if="!dialogVisible" :id="elId" :style="'font-size:15px;margin-left:'+ marginLeft+'px;width: calc(100% - '+ (marginLeft||0)+'px)'")
      el-button.editor-size-button(icon="el-icon-zoom-in" @click="dialogOpen" v-if="!btnHidden").editor-size-button
    el-dialog.monaco-editor-dialog(:visible.sync="dialogVisible" width="60%" :append-to-body="true" :show-close="false" @close="dialogClose")
      div.monaco-editor-box(:id="elId" style="height:300px;font-size:15px;width:100%")
        el-button.editor-size-button(icon="el-icon-zoom-out" @click="dialogClose").editor-size-button
</template>
<script>
import * as monaco from 'monaco-editor/esm/vs/editor/editor.api.js'
import 'monaco-editor/esm/vs/basic-languages/javascript/javascript.contribution'
import 'monaco-editor/esm/vs/basic-languages/css/css.contribution'

let idNum = 0
export default {
  props: ['value', 'marginLeft', 'lineNumbers', 'language', 'btnHidden'],
  data() {
    return {
      elId: `monaco-editor${idNum++}`,
      monacoEditor: undefined,
      monacoEditorValue: undefined,
      dialogVisible: false
    }
  },
  mounted() {
    this.initMonaco(this.value)
  },
  methods: {
    initMonaco(value) {
      let _this = this
      if (value === undefined) {
        value = ''
      }
      _this.monacoEditorValue = value
      this.monacoEditor = monaco.editor.create(document.getElementById(this.elId), {
        value: _this.monacoEditorValue + '',
        language: _this.language || 'javascript',
        theme: 'vs',
        lineNumbers: _this.lineNumbers || 'on',
        scrollBeyondLastLine: false
      })
      this.monacoEditor.onDidChangeModelContent(function () {
        let content = _this.monacoEditor.getValue()
        _this.$emit('input', content)
      })
    },
    dialogOpen() {
      let value = this.monacoEditor.getValue()
      this.dialogVisible = true
      if (this.monacoEditor) {
        this.monacoEditor.dispose()
        this.monacoEditor = undefined
      }
      this.$nextTick(() => {
        this.initMonaco(value)
      })
    },
    dialogClose() {
      let value = this.monacoEditor.getValue()
      if (this.monacoEditor) {
        this.monacoEditor.dispose()
        this.monacoEditor = undefined
      }
      this.$nextTick(() => {
        this.dialogVisible = false
        this.initMonaco(value)
      })
    }
  },
  beforeDestroy() {
    if (this.monacoEditor) {
      this.monacoEditor.dispose()
    }
  }
}
</script>
<style lang="scss">

</style>
